<template>
  <div style="height: 100%">
    <transition name="van-slide-up">
      <div class="paly-wapper" v-if="flag">
        <img :src="sonbg" alt="" class="allbg" />

        <!-- 头部 -->
        <div class="header pd15 flex">
          <van-icon name="arrow-down" @click="back" />
          <div v-if="son.sonObj">
            <div class="sonname">{{ son.sonObj[0].name }}</div>
            <div class="sonar">
              <div
                class="actorname f12"
                v-for="(item, index) in son.sonObj[0].ar"
                :key="item.id"
              >
                {{
                  index + 1 == son.sonObj[0].ar.length
                    ? item.name
                    : item.name + '/'
                }}
              </div>
            </div>
          </div>
          <div></div>
          <!-- <van-icon name="share-o" /> -->
        </div>
        <!-- 歌曲头像 -->
        <transition name="van-fade">
          <div class="content" v-show="showFlag" @click="handelshowFlag">
            <div class="cp flex">
              <img
                v-if="son.sonObj"
                :src="son.sonObj[0].al.picUrl"
                alt=""
                :class="store.state.isPlayer ? 'xuanzhuan' : 'xuanzhuanzt'"
              />
            </div>
          </div>
        </transition>
        <!-- 歌词列表 -->
        <transition name="van-fade">
          <div
            class="content2"
            ref="lyricListRef"
            v-show="!showFlag"
            @click="handelshowFlag"
          >
            <p
              class="text"
              v-for="(line, index) in currentLyric.Lyric.lines"
              :class="{ current: currentLineNum === index }"
              :key="index"
            >
              {{ line.txt }}
            </p>
          </div>
        </transition>
        <div class="bottom">
          <div class="time">
            <div class="currentTime">
              {{ store.state.currentTime }}
            </div>
            <div class="progressbar">
              <van-slider
                v-model="parvalue"
                bar-height="4px"
                active-color="#fff"
                inactive-color="#7D7878"
                @change="onChange"
              >
                <template #button>
                  <div class="custom-button"></div>
                </template>
              </van-slider>
            </div>
            <div class="duration" v-if="son.sonObj">
              {{ s_to_hs(parseInt(son.sonObj[0].dt / 1000)) }}
            </div>
          </div>
          <div class="handel">
            <i
              class="iconfont icon-xunhuan"
              v-if="store.state.PlayerStatus === 0"
              @click="checkPlayerStatus(0)"
            ></i>
            <i
              class="iconfont icon-suiji"
              v-if="store.state.PlayerStatus === 1"
              @click="checkPlayerStatus(1)"
            ></i>
            <i
              class="iconfont icon-24gl-repeatOnce2"
              v-if="store.state.PlayerStatus === 2"
              @click="checkPlayerStatus(2)"
            ></i>

            <i class="iconfont icon-shangyiqu101" @click="previous"></i>
            <i
              v-if="!store.state.isPlayer"
              class="iconfont icon-play"
              style="font-size: 48px"
              @click="player"
            ></i>
            <i
              v-else
              class="iconfont icon-zanting"
              style="font-size: 48px"
              @click="player"
            ></i>

            <i class="iconfont icon-xiayiqu101" @click="next"></i>
            <i class="iconfont icon-24gf-playlist2" @click="PlayerListshow"></i>
          </div>
        </div>
      </div>
    </transition>
    <PlayerList @init="init" />
  </div>
</template>

<script>
export default {
  name: 'playpage',
}
</script>
<script setup>
import {
  ref,
  onMounted,
  reactive,
  computed,
  onBeforeUnmount,
  watch,
  nextTick,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Lyric from '@/utlis/lyric-parser.js'
import {
  getSonUrl,
  getSondetail,
  getSonLyrics,
} from '@/service/api/playpage.js'
import { s_to_hs, random } from '@/utlis/globalfnc.js'
import axios from 'axios'
import PlayerList from '@/components/player-list'
import { showToast } from 'vant'
const store = useStore()
const route = useRoute()
const router = useRouter()

let flag = ref(false)
onMounted(() => {
  flag.value = true
})

//返回上一页
const back = () => {
  flag.value = false
  router.back(-1)
}

//进度条双向绑定
const parvalue = computed({
  get: () => {
    return store.state.parvalue
  },
  set: (val) => {
    // 调用修改进度条
    store.commit('UPDATE_PARVALUE', val)
  },
})

const updateparvalue = (e) => {
  store.commit('UPDATE_PARVALUE', e.target.value)
}

//图片 歌词切换
let showFlag = ref(true)
const handelshowFlag = () => {
  showFlag.value = !showFlag.value
}

//页面背景
let sonbg = ref('')

//歌曲详情
let son = reactive({
  sonObj: null,
  sonLyric: null,
})

//监听vuex中id的变化 变化后切换
const lisnMusicID = computed(() => {
  return store.state.musicid
})
watch(lisnMusicID, (newVal, oldVal) => {
  init(lisnMusicID.value)
})

//获取路由传过来的id
const SonIDS = route.query.encodeId

const init = async (SonID) => {
  //初始化函数，判断有没有穿ID 如果没有 用路由传过来的 如果有，用穿过来的
  if (!SonID) {
    SonID = SonIDS
  }
  //判断这一次的音乐id否和正在播放的id一致，不一致的话进行是切歌操作
  if (SonID != store.state.musicInfo.id) {
    store.commit('CHANGE_PLAYER', false)
  }

  axios
    .all([
      getSonUrl({ id: SonID }),
      getSondetail({ ids: SonID }),
      getSonLyrics({ id: SonID }),
    ])
    .then(
      axios.spread(function (res1, res2, res3) {
        // 歌曲播放地址
        const data1 = res1.data.data[0].url

        // 判断是否正在播放，如果正在播放重新赋值有可能会导致播放器初始化
        if (!store.state.isPlayer) {
          store.commit('UPDATE_MUSICSRC', data1)
        }

        const data2 = res2.data.songs
        sonbg.value = data2[0].al.picUrl
        son.sonObj = data2

        store.commit('ADD_MUSICINLIST', {
          id: SonID,
          name: son.sonObj[0].name,
          arname: son.sonObj[0].ar[0].name,
        })
        store.commit('ADD_MUSICINFO', data2[0])

        // 歌词
        const data3 = res3.data
        son.sonLyric = data3

        try {
          currentLyric.Lyric.stop()
        } catch (error) {}

        currentLyric.Lyric = new Lyric(son.sonLyric.lrc.lyric, handleLyric)

        if (store.state.isPlayer) {
          currentLyric.Lyric.stop()
          currentLyric.Lyric.seek(parseInt(globalAudio.currentTime * 1000) || 0)
        }
      })
    )
}

onMounted(() => {
  init()
})

//获取音乐播放器实例
const globalAudio = store.state.globalAudio

//监听音乐播放器实例播放，开启歌词播放
const f1 = computed(() => {
  return store.state.isPlayer
})
watch(f1, (newVal, oldVal) => {
  if (newVal) {
    currentLyric.Lyric.seek(parseInt(globalAudio.currentTime * 1000) || 0)
  }
})

const f2 = computed(() => {
  return store.state.parvalue
})
//单曲循环 歌词播放
watch(f2, (newVal, oldVal) => {
  if (parseInt(oldVal) == 100 && parseInt(newVal) == 0) {
    currentLyric.Lyric.seek(1000)
  }
})

const player = () => {
  if (store.state.isPlayer) {
    // 暂停
    globalAudio.pause()
    store.commit('CHANGE_PLAYER', false)
    currentLyric.Lyric.stop()
    console.log('暂停了')
  } else {
    // 播放
    console.log(globalAudio)
    globalAudio.play()
    store.commit('CHANGE_PLAYER', true)

    currentLyric.Lyric.seek(parseInt(globalAudio.currentTime * 1000) || 0)
  }
}

let currentLyric = reactive({
  Lyric: [],
})

let currentLineNum = ref('')
let lyricListRef = ref(null)

//歌词活动时候触发
function handleLyric({ lineNum, txt }) {
  console.log(txt)
  currentLineNum.value = lineNum
  if (lineNum > 2) {
    const lineEl = lyricListRef.value.children[lineNum]
    const lineelHeight = lineEl ? lineEl.offsetTop : 0
    lyricListRef.value.scrollTo({
      top: lineelHeight - 300,
      behavior: 'smooth',
    })
    // console.log(lineelHeight);
  }
}

// 拖动音乐进度
const onChange = (e) => {
  console.log(e)
  store.commit(
    'UPDATE_MUSICCURRENTTIMES',
    Math.round((e / 100) * globalAudio.duration)
  )
  globalAudio.play()
  store.commit('CHANGE_PLAYER', true)
  store.commit('UPDATE_PARVALUE', e)
  currentLyric.Lyric.stop()
  currentLyric.Lyric.seek(store.state.currentTimes * 1000)
}

//显示播放列表
let PlayerListFlag = ref(false)
const PlayerListshow = () => {
  store.commit('CHANGE_PLAYLIST', true)
}

/**
 * 上一曲
 */
const previous = () => {
  console.log(store.state.PlayerHistory.length)
  if (store.state.PlayerHistory.length > 1) {
    console.log(store.state.PlayerHistory[store.state.PlayerHistory.length - 2])
    store.commit(
      'UPDATE_MUSICID',
      store.state.PlayerHistory[store.state.PlayerHistory.length - 2]
    )
  } else {
    const { id } = store.state.musicInfo //拿到当前播放音乐的id
    //找出当前歌曲在播放列表的下标
    const i = store.state.musicList.findIndex((item, index) => {
      return item.id == id
    })
    if (i === 0) {
      store.commit(
        'UPDATE_MUSICID',
        store.state.musicList[store.state.musicList.length - 1].id
      )
    } else {
      store.commit('UPDATE_MUSICID', store.state.musicList[i + 1].id)
    }
  }
}
//下一曲
const next = () => {
  const { id } = store.state.musicInfo //拿到当前播放音乐的id
  //找出当前歌曲在播放列表的下标
  const i = store.state.musicList.findIndex((item, index) => {
    return item.id == id
  })
  switch (
    store.state.PlayerStatus //PlayerStatus: 0 //歌曲播放顺序：0.列表循环，1.随机播放，2.单曲循环
  ) {
    case 0: //列表循环
      if (i === store.state.musicList.length - 1) {
        store.commit('UPDATE_MUSICID', store.state.musicList[0].id)
      } else {
        store.commit('UPDATE_MUSICID', store.state.musicList[i + 1].id)
      }

      break
    case 1: //随机播放
      let ran = random(0, store.state.musicList.length) //获取随机数
      if (i === ran) {
        ran = ran + 1
      }
      store.commit('UPDATE_MUSICID', store.state.musicList[ran].id)
      break
    case 2: //单曲循环
      if (i === store.state.musicList.length - 1) {
        store.commit('UPDATE_MUSICID', store.state.musicList[0].id)
      } else {
        store.commit('UPDATE_MUSICID', store.state.musicList[i + 1].id)
      }
    default:
      break
  }
}

//切换播放列表状态
const checkPlayerStatus = (i) => {
  switch (i) {
    case 0:
      //列表循环
      showToast({
        message: '随机播放',
        position: 'bottom',
      })
      store.commit('UPDATE_PLAYERSTATUS', 1)
      break
    case 1:
      //列表循环
      showToast({
        message: '单曲循环',
        position: 'bottom',
      })
      store.commit('UPDATE_PLAYERSTATUS', 2)
      break

    case 2:
      //列表循环
      showToast({
        message: '列表循环',
        position: 'bottom',
      })
      store.commit('UPDATE_PLAYERSTATUS', 0)
      break

    default:
      break
  }
}

//离开页面回调
onBeforeUnmount(() => {
  try {
    currentLyric.Lyric.stop()
  } catch (error) {}
})
</script>
<style lang="scss" scoped>
.paly-wapper {
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: relative;
  .allbg {
    height: 100%;
    width: 100%;
    filter: blur(30px) brightness(50%);
    transform: scale(1.4);
    position: absolute;
    z-index: -1;
  }
  .header {
    color: #fff;
    text-align: center;
    .van-icon {
      font-size: 20px;
    }
    .sonar {
      display: flex;
      justify-content: center;
      .actorname {
        color: #ccc;
      }
    }
  }
  .content {
    position: absolute;
    width: 100%;
    .cp {
      height: 320px;
      width: 320px;
      margin: 60px auto;
      background-color: #000;
      background-size: 100% 100%;
      background-size: cover;
      justify-content: center;
      border-radius: 50%;
      img {
        width: 200px;
        height: 200px;
        border-radius: 50%;
      }
    }
  }
  .content2 {
    height: 70%;
    overflow-y: scroll;
    overflow-x: hidden;
    text-align: center;
    color: #afa9a9;
    margin-top: 10px;
    position: absolute;
    width: 100%;
    .current {
      color: #fff;
      transform: scale(1.2);
      transition: all 0.1s;
    }
  }
  .bottom {
    position: absolute;
    height: 110px;
    width: 100%;
    // background-color: red;
    bottom: 0;
    .time {
      color: #ccc;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 15px;
      .currentTime {
        font-size: 12px;
      }
      .progressbar {
        width: 80%;
        .van-slider {
          height: 1px !important;
          ::v-deep .van-slider__button {
            height: 12px !important;
            width: 12px !important;
          }
        }
        .custom-button {
          width: 10px;
          height: 10px;
          color: #fff;
          font-size: 10px;
          text-align: center;
          background-color: #fff;
          border-radius: 100px;
        }
      }
      .duration {
        font-size: 12px;
      }
    }
    .handel {
      padding: 30px 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 50px;
      color: #ccc;
      i {
        font-size: 20px;
      }
    }
  }
}

.xuanzhuan {
  animation: rotate 30s linear infinite;
}

.xuanzhuanzt {
  animation: rotate 30s linear infinite;
  animation-play-state: paused;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}
</style>
